package com.sunrise.gateway.shiro.redis;

import com.dap.cache.common.RedisComponentInterface;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

import java.util.Collection;
import java.util.Set;

/**
 * Edited by wangmin on 2017/6/13.
 */
public class RedisCache<K, V> implements Cache<K, V> {
    private final RedisComponentInterface jedis;
    private final String type;
    private final int expireSeconds;
    private final Class clazz;

    /**
     * 通过一个JedisManager实例构造RedisCache
     */
    public RedisCache(RedisComponentInterface jedis, String type, int expireSeconds, Class clazz) {
        this.jedis = jedis;
        this.type = type;
        this.expireSeconds = expireSeconds;
        this.clazz = clazz;
    }


    public V get(K key) throws CacheException {
        try {
            if (key == null) {
                return null;
            } else {
                @SuppressWarnings("unchecked")
                V value = (V)jedis.get(type, key.toString(), clazz);
                return value;
            }
        } catch (Throwable t) {
            throw new CacheException(t);
        }

    }


    public V put(K key, V value) throws CacheException {
        try {
            jedis.set(type, key.toString(), expireSeconds, value);
            return value;
        } catch (Throwable t) {
            throw new CacheException(t);
        }
    }


    public V remove(K key) throws CacheException {
        try {
            V previous = get(key);
            jedis.del(type, key.toString());
            return previous;
        } catch (Throwable t) {
            throw new CacheException(t);
        }
    }


    public void clear() throws CacheException {
    }

    public int size() {
        return 0;
    }

    public Set<K> keys() {
        return null;
    }

    public Collection<V> values() {
        return null;
    }
}
